package com.wishwall.web.utils;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import sun.misc.BASE64Decoder;

import com.wishwall.auth.DeviceContext;
import com.wishwall.auth.SecurityContext;
import com.wishwall.persistence.PersistenceContext;

/**
 * 
 * @author yavor.gologanov
 *
 */
public class RequestHelper {

	/**
	 * 
	 * @param request
	 * @return
	 */
	public static PersistenceContext getPersistenceContext(ServletRequest request) {
		
		String attrName = PersistenceContext.class.getCanonicalName();
		return (PersistenceContext) request.getAttribute(attrName);
		
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	public static SecurityContext getSecurityContext(ServletRequest request) {
		
		String attrName = SecurityContext.class.getCanonicalName();
		return (SecurityContext) request.getAttribute(attrName);
		
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	public static DeviceContext getDeviceContext(ServletRequest request) {
		
		String attrName = DeviceContext.class.getCanonicalName();
		return (DeviceContext) request.getAttribute(attrName);
		
	}	
	
	/**
	 * 
	 * @param request
	 */
	public static String[] getUserCredentials(ServletRequest request) throws IOException {
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String[] credentials = new String[2];
		
		String authhead = httpRequest.getHeader("Authorization");
  	    if(authhead!=null)
		{
		    //*****Decode the authorization String*****
  	    	BASE64Decoder decoder = new BASE64Decoder();  	    	
		    String usernpass = new String(decoder.decodeBuffer(authhead.substring(6)));
		    
		    //*****Split the user name from the password*****
		    credentials[0] = usernpass.substring(0,usernpass.indexOf(":"));
		    credentials[1] = usernpass.substring(usernpass.indexOf(":")+1);
		}		
  	    return credentials;
	}	
	
	/**
	 * 
	 * @param request
	 * @param context
	 */
	public static void setPersistenceContext(ServletRequest request, PersistenceContext context) {
		
		String attrName = PersistenceContext.class.getCanonicalName();
		request.setAttribute(attrName, context);
		
	}

	/**
	 * 
	 * @param request
	 * @param context
	 */
	public static void setSecurityContext(ServletRequest request, SecurityContext context) {
		
		String attrName = SecurityContext.class.getCanonicalName();
		request.setAttribute(attrName, context);
	}
		
	/**
	 * 
	 * @param request
	 * @param context
	 */
	public static void setDeviceContext(ServletRequest request, DeviceContext context) {
		
		String attrName = DeviceContext.class.getCanonicalName();
		request.setAttribute(attrName, context);
	}		
	
}
